package com.example.tests;


import org.junit.*;
import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.WebDriverWait;
import ru.esteru.selenium.factory.WebDriverFactory;

public class changeEmailTest {
  private WebDriver driver;
  private WebDriverWait wait;
  private String baseUrl;
  private StringBuffer verificationErrors = new StringBuffer();

  @Before
  public void setUp() throws Exception {
    driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
    wait = new WebDriverWait(driver, 10);
    baseUrl = "http://localhost/";
  }
 

  @Test
  public void testEmailChange() {
	goToMainPage();
    loginAs("admin", "admin");
    gotoUserProfile();
    changeEmailTo("admin@admin.ru");
    assertTrue(isOnUserManagementPage());
    logout();  
  }

	private boolean isOnUserManagementPage() {
	return  driver.findElement(By.className("content"))
			.findElement(By.tagName("h2")).getText().equals("User management");
}


	private void changeEmailTo(String string) {
		WebElement emailField = wait.until(visibilityOfElementLocated(By.id("email")));
		emailField.clear();
		emailField.sendKeys("admin@admin.com");
		wait.until(visibilityOfElementLocated(By.name("submit"))).click();

	}
		
	private void gotoUserProfile() {
		wait.until(visibilityOfElementLocated(By.linkText("My profile"))).click();
	
	}


	private void logout() {
		wait.until(visibilityOfElementLocated(By.linkText("Log out"))).click();
		wait.until(alertIsPresent()).accept();

	}
	
	private void loginAs(String username, String password) {
		WebElement userNameField = wait.until(visibilityOfElementLocated(By.id("username")));
		userNameField.clear();
	    userNameField.sendKeys(username);
	    WebElement passwordField = wait.until(visibilityOfElementLocated(By.name("password")));
	    passwordField.clear();
	    passwordField.sendKeys(password);
	    wait.until(visibilityOfElementLocated(By.name("submit"))).click();

	}
	
	private void goToMainPage() {
		driver.get(baseUrl + "/php4dvd/");
	}

  @After
  	public void tearDown() throws Exception {
	    String verificationErrorString = verificationErrors.toString();
	    if (!"".equals(verificationErrorString)) {
	      fail(verificationErrorString);
    }
  }

}
